package com.jeecms.wicool.action.car;

import static com.jeecms.common.page.SimplePage.cpn;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.wicool.entity.activities.ActivitiesApply;
import com.jeecms.wicool.entity.activities.ActivitiesApplyToExcel;
import com.jeecms.wicool.entity.car.CarAdviser;
import com.jeecms.wicool.entity.car.CarOrder;
import com.jeecms.wicool.entity.car.CarOrderAppraise;
import com.jeecms.wicool.entity.car.CarOrderToExcel;
import com.jeecms.wicool.entity.car.CarOrderToExcel2;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.car.CarAdviserMng;
import com.jeecms.wicool.manager.car.CarOrderAppraiseMng;
import com.jeecms.wicool.manager.car.CarOrderMng;
import com.jeecms.wicool.manager.util.DictionaryMng;
import com.jeecms.wicool.util.ExportExcel;

@Controller
public class CarOrderAct {
	private static final Logger log = LoggerFactory.getLogger(CarOrderAct.class);

	@RequestMapping("/carOrder/v_list.do")
	public String list(String userName,Short orderType,String orderTimeStart,String orderTimeEnd,Short status,Integer pageNo,HttpServletRequest request, ModelMap model) {
		String loginName="";
		CmsUser user=CmsUtils.getUser(request);
		Integer[] r=user.getRoleIds();
		for(Integer i:r){
			if(i==3){ //商家顾问角色
				loginName=user.getUsername();
			}
		}
		Pagination pagination = manager.getPage(loginName,userName, orderType, orderTimeStart,orderTimeEnd, status,cpn(pageNo),
				CookieUtils.getPageSize(request),CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);
		List<CarOrder> listCarOrder=(List<CarOrder>)pagination.getList();
		List<Dictionary2> listOrderType=DicMng.getList("order_type");
		List<Dictionary2> listOrderStatus=DicMng.getList("car_order_status");
		Map<String,String> map = new HashMap<String,String>();
		Map<String,String> map2 = new HashMap<String,String>();
		 for(Dictionary2 d : listOrderType){
			 map.put(d.getDicCode().toString(), d.getDicName());
		 } 
		 for(Dictionary2 d : listOrderStatus){
			 map2.put(d.getDicCode().toString(), d.getDicName());
		 } 
		 for(CarOrder p : listCarOrder){
			 if(map.containsKey(p.getOrderType().toString())){
				 p.setOrderTypeName(map.get(p.getOrderType().toString()));
			 }if(map2.containsKey(p.getStatus().toString())){
				 p.setStatusName(map2.get(p.getStatus().toString()));
			 }
		 }
		 model.addAttribute("pagination", pagination);
		model.addAttribute("listOrderType",listOrderType);
		model.addAttribute("listOrderStatus",listOrderStatus);
		model.addAttribute("orderType",orderType);
		model.addAttribute("orderTimeStart",orderTimeStart);
		model.addAttribute("orderTimeEnd",orderTimeEnd);
		model.addAttribute("userName",userName);
		model.addAttribute("status",status);
		return "car/list_carOrder";
	}
	@RequestMapping("/carOrder/v_view.do")
	public String view(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CarOrder carOrder = manager.findById(id);
		List<Dictionary2> listOrderType=DicMng.getList("order_type");
		List<Dictionary2> listOrderStatus=DicMng.getList("car_order_status");
		if(listOrderType!=null){
			for(Dictionary2 d :listOrderType){
				if(carOrder.getOrderType().equals(d.getDicCode())){
					carOrder.setOrderTypeName(d.getDicName());
				}
			}
		}if(listOrderStatus!=null){
			for(Dictionary2 d :listOrderStatus){
				if(carOrder.getStatus().equals(d.getDicCode())){
					carOrder.setStatusName(d.getDicName());
				}
			}
		}
		CarOrderAppraise carOrderAppraise = carOrderAppraiseMng.findByOrderId(id);
		if(carOrderAppraise!=null){
			model.addAttribute("carOrderAppraise",carOrderAppraise);
		}else{
			model.addAttribute("carOrderAppraise",new CarOrderAppraise());
		}
		model.addAttribute("carOrder",carOrder);
		
		return "car/view_carOrder";
	}
	@RequestMapping("/carOrder/o_isQx.do")
	public String isQx(Integer id, String userName,Short orderType,String orderTimeStart,String orderTimeEnd,Short status,Integer pageNo,HttpServletRequest request,ModelMap model) {
		WebErrors errors = validateUpdate(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CarOrder bean =  manager.findById(id);
		if(bean.getStatus().toString().equals("0")||bean.getStatus().toString().equals("1")){
			bean.setStatus(new Short("-1"));  //取消
			bean=manager.update(bean);
			model.addAttribute("message", "global.success");
		}else{
			model.addAttribute("message", "预约已经完成，不能进行取消预约操作！");
		}
	
		return list(userName, orderType, orderTimeStart,orderTimeEnd, status, pageNo, request, model);
	}
	@RequestMapping("/carOrder/o_isConfirm.do")
	public String isConfirm(Integer id,Integer adviserId, String userName,Short orderType,String orderTimeStart,String orderTimeEnd,Short status,Integer pageNo,HttpServletRequest request,ModelMap model) {
		WebErrors errors = validateUpdate(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CarOrder bean =  manager.findById(id);
		bean.setStatus(new Short("1"));  //已确认
		if (adviserId != null) {
			CarAdviser carAdviser = carAdviserMng.findById(adviserId);
			bean.setAdviser(carAdviser);
		}
		bean=manager.update(bean);
		model.addAttribute("message", "global.success");
		return list(userName, orderType, orderTimeStart,orderTimeEnd, status, pageNo, request, model);
	}
	
	@RequestMapping("/carOrder/o_isFinish.do")
	public String isFinish(Integer id, String userName,Short orderType,String orderTimeStart,String orderTimeEnd,Short status,Integer pageNo,HttpServletRequest request,ModelMap model) {
		WebErrors errors = validateUpdate(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CarOrder bean =  manager.findById(id);
		bean.setStatus(new Short("2"));  //已完成
		
		SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateTime = simpleTime.format(new Date());
		Timestamp t = Timestamp.valueOf(dateTime);
		bean.setEndTime(t);
		bean=manager.update(bean);
		model.addAttribute("message", "global.success");
		return list(userName, orderType, orderTimeStart,orderTimeEnd, status, pageNo, request, model);
	}
	@RequestMapping("/carOrder/o_delete.do")
	public String delete(Integer[] ids, String userName,Short orderType,String orderTimeStart,String orderTimeEnd ,Short status,Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		CarOrder[] beans = manager.deleteByIds(ids);
		for (CarOrder bean : beans) {
			log.info("delete CarOrder id={}", bean.getId());
			cmsLogMng.operating(request, "CarOrder.log.delete", "id="
					+ bean.getId() + ";name=" + bean.getUser().getName());
		}
		return list(userName, orderType, orderTimeStart,orderTimeEnd, status, pageNo, request, model);
	}
	private WebErrors validateSave(CarOrder bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		return errors;
	}

	@RequestMapping("/carOrder/allotAdviers.do")
	public String allotAdviers( Integer id, String userName,Short orderType,String orderTimeStart,String orderTimeEnd,Short status,Integer pageNo,HttpServletRequest request, ModelMap model) {
		List<CarAdviser> carAdviserList = carAdviserMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("adviserList",carAdviserList);
		model.addAttribute("userName",userName);
		model.addAttribute("orderType",orderType);
		model.addAttribute("orderTimeStart",orderTimeStart);
		model.addAttribute("orderTimeEnd",orderTimeEnd);
		model.addAttribute("status",status);
		model.addAttribute("pageNo",pageNo);
		model.addAttribute("id", id);
		return "car/add_carOrderAdviser";
	}
	@RequestMapping("/carOrder/v_exportExcel1.do")
	public String exportExcel1(Short orderType,String orderTimeStart,String orderTimeEnd,Integer pageNo,HttpServletRequest request,HttpServletResponse response,ModelMap model) {
		CmsUser user=CmsUtils.getUser(request);
		List<CarOrder> list = manager.getCarOrderList(orderType, orderTimeStart, orderTimeEnd, user);
		
		if(list!=null&&list.size()>0){
			ExportExcel<CarOrderToExcel> ex = new ExportExcel<CarOrderToExcel>();
			String[] headers =
				{ "序号", "预约人", "联系电话", "预约日期","预约时段","预约车系、车型","销售顾问"};
			List<CarOrderToExcel> dataset = new ArrayList<CarOrderToExcel>();
			long num=1;
			for(CarOrder c:list){
				CarOrderToExcel cte=new CarOrderToExcel();
				cte.setNum(num++);
				cte.setUserName(c.getUsername());
				cte.setMobile(c.getMobile());
				cte.setOrderDate(c.getOrderDate());
				cte.setOrderHour(c.getOrderHour());
				cte.setCarInfo(c.getCarType());
				cte.setCarAdviser(c.getAdviser()==null?"":c.getAdviser().getName());
				dataset.add(cte);
			}
			 OutputStream out ;

			try {
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				String fileName="yuyueshijia_"+df.format(new Date())+".xls";
				response.setContentType("octets/stream");
		        response.addHeader("Content-Disposition",
		                "attachment;filename="+fileName);
				out = response.getOutputStream();
				ex.exportExcel(headers, dataset, out,"yyyy-MM-dd HH:mm:ss");
				out.close();
				System.out.println("excel导出成功！");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else{
			model.addAttribute("message", "exportExcel.failed.not.have.yuyue");
		}
		return list(null, orderType, orderTimeStart, orderTimeEnd, null, pageNo, request, model);
	}
	@RequestMapping("/carOrder/v_exportExcel2.do")
	public String exportExcel2(Short orderType,String orderTimeStart,String orderTimeEnd,Integer pageNo,HttpServletRequest request,HttpServletResponse response,ModelMap model) {
		CmsUser user=CmsUtils.getUser(request);
		List<CarOrder> list = manager.getCarOrderList(orderType, orderTimeStart, orderTimeEnd, user);
		
		if(list!=null&&list.size()>0){
			ExportExcel<CarOrderToExcel2> ex = new ExportExcel<CarOrderToExcel2>();
			String[] headers =
				{ "序号", "预约人", "联系电话", "预约日期","预约时段","类型","车牌号码","客服顾问"};
			List<CarOrderToExcel2> dataset = new ArrayList<CarOrderToExcel2>();
			long num=1;
			for(CarOrder c:list){
				CarOrderToExcel2 cte=new CarOrderToExcel2();
				cte.setNum(num++);
				cte.setUserName(c.getUsername());
				cte.setMobile(c.getMobile());
				cte.setOrderDate(c.getOrderDate());
				cte.setOrderHour(c.getOrderHour());
				cte.setOrderType(c.getCarType());
				cte.setPlateNumber(c.getPlateNumber()==null?"":c.getPlateNumber());
				cte.setCarAdviser(c.getAdviser()==null?"":c.getAdviser().getName());
				dataset.add(cte);
			}
			 OutputStream out ;

			try {
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				String fileName="yuyuebaoyangweixiu_"+df.format(new Date())+".xls";
				response.setContentType("octets/stream");
		        response.addHeader("Content-Disposition",
		                "attachment;filename="+fileName);
				out = response.getOutputStream();
				ex.exportExcel(headers, dataset, out,"yyyy-MM-dd HH:mm:ss");
				out.close();
				System.out.println("excel导出成功！");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else{
			model.addAttribute("message", "exportExcel.failed.not.have.yuyue");
		}
		return list(null, orderType, orderTimeStart, orderTimeEnd, null, pageNo, request, model);
	}
	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}
	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		CarOrder entity = manager.findById(id);
		if (errors.ifNotExist(entity, CarOrder.class, id)) {
			return true;
		}
		return false;
	}
	
	@Autowired
	private CarOrderMng manager;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private CarOrderAppraiseMng carOrderAppraiseMng;
	@Autowired
	private DictionaryMng DicMng;
	@Autowired
	private CarAdviserMng carAdviserMng;
}
